package com.zhugang.stack;

/**
 * @program algorithms
 * @description: 基于两个栈实现浏览器前进、后退功能
 * @author: chanzhugang
 * @create: 2022/02/21 23:59
 */
public class BrowserOnStack {

    public static void main(String[] args) {
        BrowserOnStack browser = new BrowserOnStack();
        browser.open("1");
        browser.open("2");
        browser.open("3");

        browser.goBack();
        browser.goBack();

        browser.goForward();
        browser.goForward();
    }

    private String currentPage;
    private final StackOnLinkedList backStack;
    private final StackOnLinkedList forwardStack;

    public BrowserOnStack() {
        this.backStack = new StackOnLinkedList();
        this.forwardStack = new StackOnLinkedList();
    }


    // open
    public void open(String url) {
        if (this.currentPage != null) {
            this.backStack.push(currentPage);
            this.forwardStack.clear();
        }
        show(url, "Open");
    }


    // goBack
    public String goBack() {
        if (this.backStack.size > 0) {
            this.forwardStack.push(this.currentPage);
            String backUrl = this.backStack.pop();
            show(backUrl, "Back");
            return backUrl;
        }
        System.out.println("cannot go back");
        return null;
    }

    // goForward
    public String goForward() {
        if (this.forwardStack.size > 0) {
            this.backStack.push(this.currentPage);
            String forwardUrl = this.forwardStack.pop();
            show(forwardUrl, "Forward");
            return forwardUrl;
        }
        System.out.println("cannot goForward");
        return null;
    }

    private void show(String url, String prefix) {
        this.currentPage = url;
        System.out.println(prefix + " page ==" + url);
    }

    /**
     * 链表实现的栈
     */
    static class StackOnLinkedList {
        private Node top;
        private int size;

        public void push(String data) {
            Node node = new Node(data, top);
            top = node;
            size++;
        }

        public String pop() {
            if (top == null) {
                return null;
            }
            String data = top.data;
            top = top.next;
            size--;
            return data;
        }

        public void clear() {
            this.top = null;
            this.size = 0;

        }
    }

    /**
     * 链表
     */
    static class Node {
        private String data;
        private Node next;

        public Node(String data, Node next) {
            this.data = data;
            this.next = next;
        }

        public String getData() {
            return data;
        }

        public void setData(String data) {
            this.data = data;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }
    }
}